'use strict';

let models = require('../models');
let config = require('../../config');
let errors = config.errors;
let Session = require('../middlewares/session');

let studentService = require('../services/student');
let attendanceService = require('../services/attendance');
let festivalService = require('../services/festival');

let UserDao = models.UserDao;
let SchoolDao = models.SchoolDao;
let RoleDao = models.RoleDao;
let PrivilegeDao = models.PrivilegeDao;
let TeacherDao = models.TeacherDao;
let CardDao = models.CardDao;
let DeviceDao = models.DeviceDao;
let RawAttendanceDao = models.RawAttendanceDao;
let AttendanceValueDao = models.AttendanceValueDao;
let TrackDao = models.TrackDao;
let StudentDao = models.StudentDao;

let User = models.User;
let School = models.School;
let Privilege = models.Privilege;
let Role = models.Role;
let Teacher = models.Teacher;
let Card = models.Card;
let CardStatus = models.CardStatus;
let RawAttendance = models.RawAttendance;
let RawAttendanceType = models.RawAttendanceType;
let AttendanceValue = models.AttendanceValue;
let AttendanceStatus = models.AttendanceStatus;
let Track = models.Track;
let TrackType = models.TrackType;
let Student = models.Student;


// TODO:
// 请假检查
// 旷课检查
// 跨时间段的考勤检查
let actionEnterSchool = {
    fields: {
    },
    handler(req, res) {
        console.log(req.body);

        let card = CardDao.findOne({
            serialId: req.body.card.serialId,
            status: CardStatus.Enable
        });

        if ( !card ) {
            throw errors.CardNotFound;
        }

        let device = DeviceDao.findOne({
            serialId: req.body.card.deviceId
        });

        if ( !device ) {
            throw errors.DeviceNotFound;
        }

        let student = StudentDao.findOne({
            cards: card.id
        });

        if ( !student ) {
            throw errors.CardNotBound;
        }

        let now = new Date(req.body.timestamp);
        console.log(now);

        let existedRawAttendance = RawAttendanceDao.findOne({
            student: student,
            type: RawAttendanceType.EnterSchool,
            card: card,
            device: device,
            time: now
        });

        if ( existedRawAttendance ) {
            res.json({
                successful: true
            });
            return;
        }

        // 生成原始考勤信息
        let rawAttendance = new RawAttendance({
            student: student,
            type: RawAttendanceType.EnterSchool,
            card: card,
            device: device,
            time: now
        });

        RawAttendanceDao.create(rawAttendance);

        // 生成轨迹信息
        let track = new Track({
            student: student,
            time: now,
            card: card,
            type: TrackType.EnterSchool
        });
        TrackDao.create(track);

        student.atSchool = true;
        StudentDao.update(student);

        //let grade = studentService.getGradeOfStudent(student);
        //let school = studentService.getSchoolOfStudent(student);
        //let attendance = attendanceService.getAttendanceOfStudentToday(student);

        //// 检查节假日
        //if ( festivalService.isInFestival(now, school.festivals) ) {
        //    console.log('节假日中');
        //}
        //// 检查是否请假
        //// 检查是否迟到
        //else {
        //    let gradeValueIndex = attendanceService.lateTime(now, grade.checkTimeSet);
        //    if ( gradeValueIndex != -1 ) {
        //        console.log('迟到');
        //        let gradeValue = attendance.values[gradeValueIndex];
        //        gradeValue.enterStatus = AttendanceStatus.Late;
        //        attendanceService.updateAttendanceValues([gradeValue]);
        //    }
        //    else {
        //        let schoolValueIndex = attendanceService.lateTime(now, school.checkTimeSet);
        //        if ( schoolValueIndex != -1 ) {
        //            console.log('迟到');
        //            let schoolValue = attendance.values[schoolValueIndex];
        //            if ( schoolValue.enterStatus == AttendanceStatus.Attended ||
        //                    schoolValue.enterStatus == AttendanceStatus.Late ) {
        //                schoolValue.exitStatus = AttendanceStatus.Created;
        //            }
        //            schoolValue.enterStatus = AttendanceStatus.Late;
        //            attendanceService.updateAttendanceValues([schoolValue]);
        //        }
        //        else {
        //            console.log('正常出勤');
        //            // TODO：考虑后一天
        //            let nextValueIndex = attendanceService.nextTime(now, school.checkTimeSet);
        //            if ( nextValueIndex != -1 ) {
        //                let nextValue = attendance.values[nextValueIndex];
        //                nextValue.enterStatus = AttendanceStatus.Attended;
        //                attendanceService.updateAttendanceValues([nextValue]);
        //            }
        //        }
        //    }
        //}

        res.json({
            successful: true
        });
    }
};

let actionExitSchool = {
    handler(req, res) {
        console.log(req.body);

        let card = CardDao.findOne({
            serialId: req.body.card.serialId,
            status: CardStatus.Enable
        });

        if ( !card ) {
            throw errors.CardNotFound;
        }

        let device = DeviceDao.findOne({
            serialId: req.body.card.deviceId
        });

        if ( !device ) {
            throw errors.DeviceNotFound;
        }

        let student = StudentDao.findOne({
            cards: card.id
        });

        if ( !student ) {
            throw errors.CardNotBound;
        }

        let now = new Date(req.body.timestamp);

        let existedRawAttendance = RawAttendanceDao.findOne({
            student: student,
            type: RawAttendanceType.ExitSchool,
            card: card,
            device: device,
            time: now
        });

        if ( existedRawAttendance ) {
            res.json({
                successful: true
            });
            return;
        }

        // 生成原始考勤信息
        let rawAttendance = new RawAttendance({
            student: student,
            type: RawAttendanceType.ExitSchool,
            card: card,
            device: device,
            time: now
        });

        RawAttendanceDao.create(rawAttendance);

        // 生成轨迹信息
        let track = new Track({
            student: student,
            time: now,
            type: TrackType.ExitSchool
        });
        TrackDao.create(track);

        student.atSchool = false;
        StudentDao.update(student);

        //let grade = studentService.getGradeOfStudent(student);
        //let school = studentService.getSchoolOfStudent(student);
        //let attendance = attendanceService.getAttendanceOfStudentToday(student);

        //// 检查节假日
        //if ( festivalService.isInFestival(now, school.festivals) ) {
        //    console.log('节假日中');
        //}
        //// 检查是否请假
        //// 检查是否早退
        //else {
        //    let gradeValueIndex = attendanceService.earlyTime(now, grade.checkTimeSet);
        //    if ( gradeValueIndex != -1 ) {
        //        console.log('早退');
        //        let gradeValue = attendance.values[gradeValueIndex];
        //        gradeValue.exitStatus = AttendanceStatus.Early;
        //        attendanceService.updateAttendanceValues([gradeValue]);
        //    }
        //    else {
        //        let schoolValueIndex = attendanceService.earlyTime(now, school.checkTimeSet);
        //        if ( schoolValueIndex != -1 ) {
        //            console.log('早退');
        //            let schoolValue = attendance.values[schoolValueIndex];
        //            schoolValue.exitStatus = AttendanceStatus.Early;
        //            attendanceService.updateAttendanceValues([schoolValue]);
        //        }
        //        else {
        //            console.log('正常出勤');
        //            // 初始化下一时段的考勤状态
        //            // TODO：考虑后一天
        //            let nextValueIndex = attendanceService.nextTime(now, school.checkTimeSet);
        //            if ( nextValueIndex != -1 ) {
        //                let nextValue = attendance.values[nextValueIndex];
        //                nextValue.enterStatus = AttendanceStatus.Created;
        //                attendanceService.updateAttendanceValues([nextValue]);
        //            }
        //            
        //            // 设置上一时段的考勤状态
        //            // TODO：考虑前一天
        //            let lastValueIndex = attendanceService.lastTime(now, school.checkTimeSet);
        //            if ( lastValueIndex != -1 ) {
        //                let lastValue = attendance.values[lastValueIndex];
        //                if ( lastValue.exitStatus == AttendanceStatus.Created ) {
        //                    lastValue.exitStatus = AttendanceStatus.Attended;
        //                }
        //                attendanceService.updateAttendanceValues([lastValue]);
        //            }
        //        }
        //    }
        //}

        res.json({
            successful: true
        });
    }
};

let actionEnterClassroom = {
    handler(req, res) {
    }
};

let actionExitClassroom = {
    handler(req, res) {
    }
};

module.exports = {
    actionEnterSchool,
    actionExitSchool,
    actionEnterClassroom,
    actionExitClassroom
};
